package com.hspedu.newData.dmsxl.树.二叉树的遍历.层序遍历迭代法.队列;

import com.hspedu.newData.dmsxl.ds.TreeNode;
import org.junit.Test;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-23 
 * @Version: 1.0
 */

public class LC101对称二叉树 {

    // 迭代法,普通队列
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root.left);
        queue.offer(root.right);
        while(!queue.isEmpty()){
            TreeNode leftNode = queue.poll();
            TreeNode rightNode = queue.poll();

            if (leftNode == null && rightNode == null){
                continue;
            }
            if (leftNode == null || rightNode == null || rightNode.val != leftNode.val){
                return false;
            }
            queue.offer(leftNode.left);
            queue.offer(rightNode.right);
            queue.offer(leftNode.right);
            queue.offer(rightNode.left);
        }
        return true;
    }

    // 迭代法，双端队列
    public boolean isSymmetric1(TreeNode root) {

        Deque<TreeNode> deque = new LinkedList<>();

        deque.addFirst(root.left);
        deque.addLast(root.right);

        while(!deque.isEmpty()){
            TreeNode left = deque.pollFirst();
            TreeNode right = deque.pollLast();

            if (left == null && right == null){
                continue;
            }
            if (left == null || right == null || left.val != right.val){
                return false;
            }

            deque.addFirst(left.left);
            deque.addLast(right.right);
            deque.addFirst(left.right);
            deque.addLast(right.left);
        }

        return true;
    }

    // 递归法
    public boolean isSymmetric2(TreeNode root) {

        boolean compare = compare(root.left, root.right);
        return compare;
    }

    public boolean compare(TreeNode left,TreeNode right){
        if (left == null && right == null){
            return true;
        }

        if (left == null || right == null || left.val != right.val){
            return false;
        }

        boolean outSide = compare(left.left, right.right);
        boolean inSide = compare(left.right, right.left);

        return outSide && inSide;
    }



    @Test
    public void test() {
        // 测试代码

        TreeNode t7 = new TreeNode(2);
        TreeNode t6 = new TreeNode(5);
        TreeNode t5 = new TreeNode(5);
        TreeNode t4 = new TreeNode(3);
        TreeNode t3 = new TreeNode(2,t6,t7);
        TreeNode t2 = new TreeNode(2,t4,t5);
        TreeNode t1 = new TreeNode(1,t2,t3);

        boolean symmetric = isSymmetric2(t1);
        System.out.println("==========");

    }
}
